import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function POST(request: Request) {
    // 解析 FormData
    const formData = await request.formData();
    const imageName = formData.get('imageName') as string;
    const labels = JSON.parse(formData.get('labels') as string);
    const imageWidth = parseInt(formData.get('imageWidth') as string, 10);
    const imageHeight = parseInt(formData.get('imageHeight') as string, 10);
    const imageFile = formData.get('image') as File;

    console.log(imageName, labels, imageWidth, imageHeight);

    // 处理标签数据
    const labelData = labels.map((label: any) => {
        const centerX = ((label.startX + label.endX) / 2) / imageWidth;
        const centerY = ((label.startY + label.endY) / 2) / imageHeight;
        const width = Math.abs(label.endX - label.startX) / imageWidth;
        const height = Math.abs(label.endY - label.startY) / imageHeight;
        const classId = label.labelIndex; // 假设所有标签的 class_id 为 0

        return `${classId} ${centerX} ${centerY} ${width} ${height}`;
    }).join('\n');

    // 保存标签数据到文件
    const labelFilePath = path.join(process.cwd(), 'ultralytics/project/demo/train-folder/labels/train', `${imageName.split('.').slice(0, -1).join('.')}.txt`);
    fs.writeFileSync(labelFilePath, labelData, 'utf8');

    // 保存图像文件
    const imageFilePath = path.join(process.cwd(), 'ultralytics/project/demo/train-folder/images/train', imageName);
    const buffer = Buffer.from(await imageFile.arrayBuffer());
    fs.writeFileSync(imageFilePath, buffer);

    return NextResponse.json({ message: '标签和图像已保存' });
}
